layui.define((exports) => {
    "use strict";

    let $ = layui.$
    let layer = layui.layer
    let element = layui.element
    let is_mobile = false
    let dropdown = layui.dropdown
    let form = layui.form
    let model_menu

    let theme_head = []

    let theme_menu = []

    let theme_logo = []

    let layui_data = layui.data("admin")

    // 初始化
    let options = {
        menu_api: "", // 菜单接口
        theme_api: "", // 主题接口
        theme_head: 0,// 头部主题
        theme_menu: 1,// 左侧主题
        theme_logo: 1,// logo主题
        footer: true // 页脚
    }

    /**
     * 左侧栏开关
     * @param {boolean} off 
     */
    let menuLeft = (off) => {
        if (off) {
            if (is_mobile) {
                let side = $(".admin .layui-side").html()
                let logo = $(".admin .layui-logo").html()
                model_menu = layer.open({
                    type: 1,
                    title: false,
                    content: `<div class="mobile-menu layui-layout layui-layout-admin">
                            <div class="layui-header"><div class="admin layui-logo">${logo}</div></div>
                            <div class="admin layui-side">${side}</div>
                            </div>`,
                    area: ['230px', '100%'],
                    offset: 'l',
                    anim: 'slideRight', // 从左往右
                    shadeClose: true,
                    closeBtn: 0,
                    success: () => {
                        element.render('nav', 'menuLeft');
                    }
                });
            } else {
                $(".admin .layui-logo").css("width", "230px")
                $(".admin .layui-layout-admin").css("width", "230px")
                $(".admin .layui-side").css("width", "230px")

                $(".admin .layui-body").css("left", "230px")
                $(".admin .layui-layout-left").css("left", "230px")
                $(".admin .layui-layout-admin .layui-footer").css("left", "230px")

                $(`[kb-event="menuLeft"] a`)
                    .html('<i class="layui-icon layui-icon-shrink-right"></i>')
            }
        } else {
            if (is_mobile) {
                layer.close(model_menu)
            }
            $(".admin .layui-logo").css("width", "0px")
            $(".admin .layui-layout-admin").css("width", "0px")
            $(".admin .layui-side").css("width", "0px")

            $(".admin .layui-body").css("left", "0px")
            $(".admin .layui-layout-left").css("left", "0px")
            $(".admin .layui-layout-admin .layui-footer").css("left", "0px")

            $(`[kb-event="menuLeft"] a`)
                .html('<i class="layui-icon layui-icon-spread-left"></i>')
        }
    }

    /**
     * 窗口宽度函数
     * @param {number} width 
     */
    let fun_model = (width = $(window).width()) => {
        if (width < 768) {
            is_mobile = true;
            menuLeft(false)
        } else {
            is_mobile = false
            menuLeft(true)
        }
    }

    // 监听窗口宽度变化
    $(window).resize(function () {
        fun_model($(window).width())
    });

    // 触发->窗口宽度函数
    fun_model()

    /**
     * 添加tab
     * @param {string} title 
     * @param {string} url 
     */
    let add_tab = (title, url) => {
        element.tabAdd("menuTab", {
            title: title,
            content: `<iframe src="${url}" frameborder="0"></iframe>`,
            id: url,
            change: true
        })
    }

    // 添加tab
    element.on('nav(menuLeft)', (elem) => {
        let title = elem.text()
        let url = elem.attr("kb-href")
        if (typeof url !== "undefined" && url != "") {
            let then = $(`.admin .layui-tab [lay-id="${url}"]`)
            if (then.length > 0) {
                element.tabChange("menuTab", url)
            } else {
                add_tab(title, url)
            }
            layer.close(model_menu)
        }
    })

    // 左侧导航 按钮
    $("body").delegate("[kb-event='menuLeft']", "click", () => {
        let str = $(`[kb-event="menuLeft"] a i`).attr("class")
        if (str === "layui-icon layui-icon-spread-left") {
            menuLeft(true)
        } else {
            menuLeft(false)
        }
    });

    /**
     * 多框架主题变更
     * @param {string} href 
     */
    let theme_iframe_all = (href) => {
        let iframe = $("iframe")
        iframe.each((k, v) => {
            let targetElement = v.contentWindow.document.getElementById("layui_theme_css")
            $(targetElement).attr("href", href)
        })
    }

    // 主图样式切换
    $("body").delegate("[kb-event='layui_theme_css']", "click", () => {
        let side_bg = $(".admin .layui-side-scroll .layui-bg-gray")
        if ($("[kb-event='layui_theme_css'] i").attr("class") === "layui-icon layui-icon-light") {
            $("#layui_theme_css").attr("href", $("#layui_theme_css").attr("data"))
            theme_iframe_all($("#layui_theme_css").attr("data"))
            $("[kb-event='layui_theme_css'] i").attr("class", "layui-icon layui-icon-moon")
            if (side_bg.length) {
                side_bg.css("background", "#232324")
            }
        } else {
            $("#layui_theme_css").attr("href", "")
            theme_iframe_all("")
            $("[kb-event='layui_theme_css'] i").attr("class", "layui-icon layui-icon-light")
            if (side_bg.length) {
                side_bg.css("background", "#fafafa")
            }
        }
    })

    // 刷新页面
    $("body").delegate("[kb-event='refresh']", "click", () => {
        let src = $(".admin .layui-tab-content .layui-show iframe").attr("src")
        $(".admin .layui-tab-content .layui-show iframe")
            .attr("src", src);
    })

    /**
     * 进入全屏
     */
    let fullScreen = () => {
        var el = document.documentElement;
        var rfs = el.requestFullScreen || el.webkitRequestFullScreen;
        if (typeof rfs != "undefined" && rfs) {
            rfs.call(el);
        } else if (typeof window.ActiveXObject != "undefined") {
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript != null) {
                wscript.SendKeys("{F11}");
            }
        } else if (el.msRequestFullscreen) {
            el.msRequestFullscreen();
        } else if (el.oRequestFullscreen) {
            el.oRequestFullscreen();
        } else if (el.webkitRequestFullscreen) {
            el.webkitRequestFullscreen();
        } else if (el.mozRequestFullScreen) {
            el.mozRequestFullScreen();
        } else {
            miniAdmin.error('浏览器不支持全屏调用！');
        }
    }

    /**
     * 退出全屏
     */
    let exitFullScreen = () => {
        var el = document;
        var cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.exitFullScreen;
        if (typeof cfs != "undefined" && cfs) {
            cfs.call(el);
        } else if (typeof window.ActiveXObject != "undefined") {
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript != null) {
                wscript.SendKeys("{F11}");
            }
        } else if (el.msExitFullscreen) {
            el.msExitFullscreen();
        } else if (el.oRequestFullscreen) {
            el.oCancelFullScreen();
        } else if (el.mozCancelFullScreen) {
            el.mozCancelFullScreen();
        } else if (el.webkitCancelFullScreen) {
            el.webkitCancelFullScreen();
        } else {
            miniAdmin.error('浏览器不支持全屏调用！');
        }
    }

    // 全屏开关
    $("body").delegate(`[kb-event="fullscreen"]`, "click", () => {
        if ($(`[kb-event="fullscreen"] i`).attr("class") === "layui-icon layui-icon-screen-restore") {
            exitFullScreen()
            $(`[kb-event="fullscreen"] i`).attr("class", "layui-icon layui-icon-screen-full")
            $(`[kb-event="fullscreen"] a`).attr("title", "全屏")
        } else {
            fullScreen()
            $(`[kb-event="fullscreen"] i`).attr("class", "layui-icon layui-icon-screen-restore")
            $(`[kb-event="fullscreen"] a`).attr("title", "退出全屏")
        }
    })

    // 右键tab
    $(document).on('contextmenu', '.admin .layui-body .layui-tab li', function (e) {
        e.preventDefault(); // 阻止默认的右键菜单
        let then = $(this)
        let this_id = then.attr("lay-id");
        let arr = [
            { title: "关闭全部", "id": "closeall" }
        ]
        if (typeof this_id !== "undefined" && this_id != "0") {
            arr.unshift(
                { title: "关闭当前", "id": "close" },
                { title: "关闭其他", "id": "closeother" }
            )
        }
        dropdown.render({
            elem: this,
            show: true,
            trigger: "contextmenu",
            data: arr,
            click: function (obj) {
                switch (obj.id) {
                    case "close":
                        element.tabDelete("menuTab", this_id)
                        break
                    case "closeother":
                        $('.admin .layui-body .layui-tab li').each((k, v) => {
                            let del_id = $(v).attr("lay-id")
                            if (typeof del_id !== "undefined" && del_id != this_id) {
                                element.tabDelete("menuTab", del_id)
                            }
                        })
                        break
                    case "closeall":
                        $('.admin .layui-body .layui-tab li').each((k, v) => {
                            let del_id = $(v).attr("lay-id")
                            if (typeof del_id !== "undefined") {
                                element.tabDelete("menuTab", del_id)
                            }
                        })
                        break
                }
            }
        });
    });

    // 右侧菜单
    $("body").delegate("[kb-event='menuRight']", "click", () => {
        let theme_head_str = "";
        theme_head.forEach((v, k) => {
            let this_str = layui_data.theme_head == k ? " class='this'" : "";
            theme_head_str += `<div${this_str}>
            <a href="javascript:;" title="${v.title}" class="color" style="background:${v.color};"></a>
            </div>`
        })
        let theme_menu_str = "";
        theme_menu.forEach((v, k) => {
            let this_str = layui_data.theme_menu == k ? " class='this'" : "";
            theme_menu_str += `<div${this_str}>
            <a href="javascript:;" title="${v.title}" class="color" style="background:${v.color};"></a>
            </div>`
        })
        let theme_logo_str = "";
        theme_logo.forEach((v, k) => {
            let this_str = layui_data.theme_logo == k ? " class='this'" : "";
            theme_logo_str += `<div ${this_str}>
            <a href="javascript:;" title="${v.color}" class="color" style="background:${v.color};"></a>
            </div>`
        })
        layer.open({
            type: 1,
            title: false,
            content: `<div class="layui-layer-content layui-form">
            <div class="pearone-color">
                <div class="color-title">LOGO</div>
                <div class="color-content">
                    <div class="theme-color" type="logo">
                        ${theme_logo_str}
                    </div>
                </div>
            </div>
            <div class="pearone-color">
                <div class="color-title">菜单风格</div>
                <div class="color-content">
                    <div class="theme-color" type="menu">
                        ${theme_menu_str}
                    </div>
                </div>
            </div>
            <div class="pearone-color">
                <div class="color-title">标头风格</div>
                <div class="color-content">
                    <div class="theme-color" type="head">
                        ${theme_head_str}
                    </div>
                </div>
            </div>
            <div class="pearone-color">
                <div class="color-title">更多设置</div>
                <div class="color-content">
                    <div class="layui-form-item">
                        <div class="layui-input-inline" style="width:210px;">
                            <input type="checkbox" lay-filter="footer-page" title="开启|关闭" lay-skin="switch" ${options.footer ? "checked" : ""}>
                        </div>
                        <span class="set-text">开启页脚</span>
                    </div>
                </div>
            </div>
            </div>`,
            area: ['320px', '100%'],
            offset: 'r',
            anim: 'slideLeft', // 从左往右
            shadeClose: true,
            closeBtn: 0,
            success: () => {
                form.render()
            }
        });
    })

    /**
     * 切换主题
     */
    let theme_fun = (type, index = 0) => {
        switch (type) {
            case "menu":
                let menu = theme_menu[index]
                let menu_nav = $(".admin .layui-side-scroll .layui-nav")
                menu_nav.attr("class", `layui-nav layui-nav-tree ${menu.title}`)
                menu_nav.parent().parent().attr("class", `layui-side ${menu.title}`)
                layui.data("admin", {
                    key: "theme_menu",
                    value: index
                })
                break
            case "head":
                let head = theme_head[index]
                let head_nav = $(".admin .layui-header")
                head_nav.attr("class", `layui-header ${head.title}`)
                head_nav.find("a").css("color", head.text)
                head_nav.find("i").css("color", head.text)
                layui.data("admin", {
                    key: "theme_head",
                    value: index
                })
                break
            case "logo":
                let logo = theme_logo[index]
                let logo_nav = $(".admin .layui-header .layui-logo")
                logo_nav.css("background", `${logo.color}`)
                logo_nav.css("color", logo.text)
                layui.data("admin", {
                    key: "theme_logo",
                    value: index
                })
                break
        }
        layui_data = layui.data("admin")
    }

    // 点击主题
    $("body").delegate(".pearone-color .theme-color div", "click", function () {
        let type = $(this).parent().attr("type")
        let index = $(this).index()
        theme_fun(type, index)
        $(this).parent().children(".this").removeClass("this")
        $(this).addClass("this")
    })

    /**
     * 页脚函数
     * @param {boolean} checked 
     */
    let footer_fun = (checked) => {
        if (checked) {
            $(".admin .layui-footer").show()
            $(".admin .layui-layout-admin .layui-body").css("padding-bottom", "44px")
            $(".admin .layui-body .layui-tab-content .layui-tab-item").css("padding-bottom", "54px")
        } else {
            $(".admin .layui-footer").hide()
            $(".admin .layui-layout-admin .layui-body").css("padding-bottom", "0px")
            $(".admin .layui-body .layui-tab-content .layui-tab-item").css("padding-bottom", "10px")
        }
    }

    // 点击页脚
    form.on('switch(footer-page)', function (data) {
        let elem = data.elem; // 获得 checkbox 原始 DOM 对象
        let checked = elem.checked; // 获得 checkbox 选中状态
        footer_fun(checked)
        options.footer = checked
    })

    /**
     * 渲染菜单函数
     * @param {string} api 
     */
    let render_menu = (api) => {
        $.get(api, (res) => {
            if (res.code == 0) {
                menu_fun(res.data)
            } else {
                throw new Error("获取菜单接口失败");
            }
        })
    }

    /**
     * 主题接口
     * @param {string} api 
     */
    let theme_api = (api) => {
        $.get(api, (res) => {
            if (res.code == 0) {
                theme_head = res.data.theme_head
                theme_logo = res.data.theme_logo
                theme_menu = res.data.theme_menu

                theme_fun("menu", layui_data.theme_menu)
                theme_fun("head", layui_data.theme_head)
                theme_fun("logo", layui_data.theme_logo)
            } else {
                throw new Error("获取主题接口失败");
            }
        })
    }

    /**
     * 子菜单遍历
     * @param {Array} data 
     * @return {string}
     */
    let menu_child_fun = (data) => {
        let html = `<dl class="layui-nav-child">`
        data.forEach((v, k) => {
            html += `<dd>`
            let i = v.icon.trim() != "" ? `<i class="layui-icon ${v.icon}"></i>` : "";
            let href = v.href.trim() != "" ? `kb-href="${v.href}"` : "";
            html += `<a href="javascript:;" ${href}>${i}<span>${v.title}</span></a>`
            if (v.children && v.children.length > 0) {
                html += menu_child_fun(v.children);
            }
            html += `</dd>`
        })
        html += `</dl>`
        return html
    }

    /**
     * 遍历菜单函数
     * @param {Array} data 
     */
    let menu_fun = (data) => {
        $(".admin .layui-side .layui-nav").html("")
        let html = ""
        data.forEach((v, k) => {
            let i = v.icon.trim() != "" ? `<i class="layui-icon ${v.icon}"></i>` : "";
            let href = v.href.trim() != "" ? `kb-href="${v.href}"` : "";
            html += `<li class="layui-nav-item"><a href="javascript:;" ${href}>${i}<span>${v.title}</span></a>`
            if (v.children && v.children.length > 0) {
                html += menu_child_fun(v.children);
            }
            html += `</li>`
        })
        $(".admin .layui-side .layui-nav").html(html)
        element.render('nav', 'menuLeft');
    }

    let admin = {
        // 渲染
        render: (object) => {
            options.footer = object.footer || options.footer;
            options.menu_api = object.menu_api || options.menu_api;
            options.theme_api = object.theme_api || options.theme_api;
            options.theme_menu = object.theme_menu || options.theme_menu;
            options.theme_head = object.theme_head || options.theme_head;
            options.theme_logo = object.theme_logo || options.theme_logo;
            if (Object.keys(layui_data).length === 0 && layui_data.constructor === Object) {
                layui.data('admin', {
                    key: "theme_menu",
                    value: options.theme_menu
                });
                layui.data('admin', {
                    key: "theme_head",
                    value: options.theme_head
                });
                layui.data('admin', {
                    key: "theme_logo",
                    value: options.theme_logo
                });
                layui.data('admin', {
                    key: "footer",
                    value: options.footer
                });
                layui_data = layui.data("admin")
            }
            footer_fun(layui_data.footer)
            theme_api(object.theme_api)
            render_menu(options.menu_api)
        },
        // 重载菜单
        reloadMenu: () => {
            render_menu(options.menu_api)
        }
    }

    // 加载动画
    window.onload = () => {
        setTimeout(() => {
            $(".loader-main").hide();
        }, 1000)
    };

    exports('admin', admin);
})